import { StackActions, useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useCallback, useRef, useState } from 'react';
import { StatusBar, StyleSheet, Text, View, ScrollView, TouchableOpacity, Image, FlatList } from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Video from 'react-native-video';

import FastImage from '@d11/react-native-fast-image';

import useHome from './home';
import HomeHeaderBar from '@/components/homeHeaderBar';
import { RootStackParamList } from '@/types/navigation';
import { pxToVh, pxToVw } from '@/utils/pxToVx';

const Home = () => {
  const { celebrityData, templateData, activeCategory, setActiveCategory } = useHome();
  const insets = useSafeAreaInsets();
  const [playing, setPlaying] = useState<string | null>(null);
  const scrollViewRef = useRef<ScrollView>(null);
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();

  // const renderCelebrityItem = ({ item }: { item: Celebrity }) => (
  //   <TouchableOpacity style={styles.celebrityItem}>
  //     <FastImage source={{ uri: item.imageUrl }} style={styles.celebrityImage} resizeMode="cover" />
  //     <Text style={styles.celebrityName} numberOfLines={1}>
  //       {item.name}
  //     </Text>
  //   </TouchableOpacity>
  // );

  // const handlePlayPause = useCallback((id: string) => {
  //   setPlaying((prev) => (prev === id ? null : id));
  // }, []);

  const handleScroll = useCallback(() => {
    // Pause video when scrolling
    if (playing) {
      setPlaying(null);
    }
  }, [playing]);

  const handleMoreCelebrities = useCallback(() => {
    navigation.dispatch(StackActions.push('SelectCelebrity'));
  }, [navigation]);

  const renderTemplateItem = ({ item }: { item: Face.Template }) => {
    const isPlaying = playing === item.id;

    return (
      <TouchableOpacity
        style={styles.templateItem}
        onPress={() => {
          // If this is a birthday template, navigate to BirthdayWishes screen
          // if (item.title.toLowerCase().includes('birthday')) {
          navigation.navigate('BirthdayWishes');
          // } else {
          //   handlePlayPause(item.id);
          // }
        }}
      >
        <View>
          <View style={styles.templateVideoContainer}>
            <Video
              source={{ uri: item.videoFile }}
              style={styles.templateVideo}
              resizeMode="cover"
              repeat
              // paused={!isPlaying}
              muted={true}
            />
          </View>

          <View style={styles.templateInfo}>
            <Text style={styles.templateTitle}>{item.title}</Text>
            {item.description && <Text style={styles.templateDescription}>{item.description}</Text>}
          </View>
        </View>
      </TouchableOpacity>
    );
  };

  const itemPress = (item: Face.Celebrity) => {
    console.log('start======================');
    console.log('item = ', item);
    console.log('end========================');

    navigation.navigate('EnterText', { celebrity: item });
  };

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <HomeHeaderBar />
      <StatusBar backgroundColor={'rgba(246, 252, 255, 1)'} />

      <ScrollView
        ref={scrollViewRef}
        style={styles.scrollView}
        showsVerticalScrollIndicator={false}
        onScroll={handleScroll}
        scrollEventThrottle={16}
      >
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Create with Celebrities</Text>
          <TouchableOpacity style={styles.moreButton} onPress={handleMoreCelebrities}>
            <Text style={styles.moreButtonText}>MORE</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.categoryTabsContainer}>
          <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.categoryTabs}>
            {['All', 'Popular', 'New', 'Traditional'].map((category) => (
              <TouchableOpacity
                key={category}
                style={[styles.categoryTab, activeCategory === category && styles.activeCategoryTab]}
                onPress={() => setActiveCategory(category)}
              >
                <Text style={[styles.categoryTabText, activeCategory === category && styles.activeCategoryTabText]}>
                  {category}
                </Text>
              </TouchableOpacity>
            ))}
          </ScrollView>
        </View>

        {/* Celebrity grid with horizontal scrolling for both rows */}
        <View style={styles.celebrityGridContainer}>
          <ScrollView
            horizontal
            showsHorizontalScrollIndicator={false}
            contentContainerStyle={styles.celebrityGridContent}
          >
            <View style={styles.celebrityGrid}>
              {/* First Row */}
              <View style={styles.celebrityRow}>
                {celebrityData.length > 0 &&
                  celebrityData.slice(0, Math.ceil(celebrityData.length / 2)).map((item) => (
                    <TouchableOpacity
                      key={`row1-${item.id}`}
                      style={styles.celebrityItem}
                      onPress={() => itemPress(item)}
                    >
                      <FastImage source={{ uri: item.avtarUrl }} style={styles.celebrityImage} resizeMode="cover" />
                      <Text style={styles.celebrityName} numberOfLines={1}>
                        {item.name}
                      </Text>
                    </TouchableOpacity>
                  ))}
              </View>

              {/* Second Row */}
              <View style={styles.celebrityRow}>
                {celebrityData.length > 0 &&
                  celebrityData.slice(Math.ceil(celebrityData.length / 2)).map((item) => (
                    <TouchableOpacity
                      key={`row2-${item.id}`}
                      style={styles.celebrityItem}
                      onPress={() => itemPress(item)}
                    >
                      <FastImage source={{ uri: item.avtarUrl }} style={styles.celebrityImage} resizeMode="cover" />
                      <Text style={styles.celebrityName} numberOfLines={1}>
                        {item.name}
                      </Text>
                    </TouchableOpacity>
                  ))}
              </View>
            </View>
          </ScrollView>
        </View>

        <View style={styles.sectionTopicTemplates}>
          <Text style={styles.sectionTitle}>Topic Templates</Text>
        </View>

        <FlatList
          data={templateData}
          renderItem={renderTemplateItem}
          keyExtractor={(item) => item.id}
          showsVerticalScrollIndicator={false}
          scrollEnabled={false}
          style={styles.templateList}
          contentContainerStyle={styles.templateListContent}
        />
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#fff',
    flex: 1,
  },
  scrollView: {
    flex: 1,
  },
  section: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: pxToVw(20),
    marginTop: pxToVh(10),
  },
  sectionTitle: {
    fontSize: pxToVh(18),
    fontWeight: '600',
    color: '#333',
  },
  moreButton: {
    backgroundColor: '#F0F7FF',
    paddingHorizontal: pxToVw(15),
    paddingVertical: pxToVh(5),
    borderRadius: 20,
    alignItems: 'center',
    justifyContent: 'center',
  },
  moreButtonText: {
    fontSize: pxToVh(12),
    color: '#3B82F6',
    fontWeight: '500',
  },
  categoryTabsContainer: {
    marginTop: pxToVh(15),
  },
  categoryTabs: {
    flexDirection: 'row',
    paddingHorizontal: pxToVw(20),
  },
  categoryTab: {
    marginRight: pxToVw(15),
    paddingVertical: pxToVh(8),
    paddingHorizontal: pxToVw(15),
    borderRadius: 20,
  },
  activeCategoryTab: {
    backgroundColor: '#3B82F6',
  },
  categoryTabText: {
    fontSize: pxToVh(14),
    color: '#666',
  },
  activeCategoryTabText: {
    color: '#FFFFFF',
    fontWeight: '500',
  },
  celebrityGridContainer: {
    marginTop: pxToVh(15),
    paddingHorizontal: pxToVw(20),
  },
  celebrityGridContent: {
    paddingRight: pxToVw(20),
  },
  celebrityGrid: {
    flexDirection: 'column',
  },
  celebrityRow: {
    flexDirection: 'row',
    marginBottom: pxToVh(10),
  },
  celebrityItem: {
    marginRight: pxToVw(20),
    alignItems: 'center',
    width: pxToVw(65),
  },
  celebrityImage: {
    width: pxToVw(65),
    height: pxToVw(65),
    borderRadius: pxToVw(32.5),
    backgroundColor: '#f0f0f0',
  },
  celebrityName: {
    fontSize: pxToVh(12),
    color: '#333',
    marginTop: pxToVh(5),
    textAlign: 'center',
    width: pxToVw(65),
  },
  sectionTopicTemplates: {
    paddingHorizontal: pxToVw(20),
    marginTop: pxToVh(15),
    marginBottom: pxToVh(15),
  },
  templateList: {
    marginBottom: pxToVh(20),
  },
  templateListContent: {
    paddingHorizontal: pxToVw(20),
  },
  templateItem: {
    marginBottom: pxToVh(15),
    borderRadius: 10,
    overflow: 'hidden',
    backgroundColor: '#fff',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3,
    elevation: 3,
  },
  templateVideoContainer: {
    height: pxToVh(180),
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    justifyContent: 'center',
    alignItems: 'center',
    overflow: 'hidden',
    backgroundColor: '#e0f7ff',
  },
  templateVideo: {
    width: '100%',
    height: '100%',
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
  },
  playButtonContainer: {
    position: 'absolute',
    justifyContent: 'center',
    alignItems: 'center',
  },
  playButton: {
    width: pxToVw(50),
    height: pxToVw(50),
    borderRadius: pxToVw(25),
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.3,
    shadowRadius: 3,
    elevation: 5,
  },
  playIconTriangle: {
    width: 0,
    height: 0,
    borderStyle: 'solid',
    borderLeftWidth: pxToVw(10),
    borderRightWidth: pxToVw(10),
    borderBottomWidth: pxToVw(16),
    borderLeftColor: 'transparent',
    borderRightColor: 'transparent',
    borderBottomColor: 'white',
    transform: [{ rotate: '90deg' }],
    marginLeft: pxToVw(3), // To center the triangle
  },
  pauseIconContainer: {
    flexDirection: 'row',
    width: pxToVw(18),
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  pauseBar: {
    width: pxToVw(6),
    height: pxToVw(18),
    backgroundColor: 'white',
    borderRadius: pxToVw(2),
  },
  templateInfo: {
    padding: pxToVw(15),
    marginTop: pxToVh(0),
    backgroundColor: '#fff',
    borderBottomLeftRadius: 10,
    borderBottomRightRadius: 10,
  },
  templateTitle: {
    fontSize: pxToVh(16),
    fontWeight: '600',
    color: '#000',
  },
  templateDescription: {
    fontSize: pxToVh(12),
    color: '#666',
    marginTop: pxToVh(4),
  },
});

export default Home;
